# Title     : TODO
# Objective : TODO
# Created by: Administrator
# Created on: 2019/6/18

createWhenNoExist <- function(f) {
  !dir.exists(f) && dir.create(f)
}

library(gplots)
library(optparse)
library(ropls)
library(magrittr)
library(ComplexHeatmap)
library(tidyverse)

option_list <- list(
  make_option("--i", default = "AllMet_Raw.txt", type = "character", help = "metabolite data file"),
  make_option("--g", default = "SampleInfo.csv", type = "character", help = "sample group file"),
  make_option("--config", default = "calculate_config.txt", type = "character", help = "config file")
)
opt <- parse_args(OptionParser(option_list = option_list))

args <- commandArgs(trailingOnly = F)
scriptPath <- dirname(sub("--file=", "", args[grep("--file", args)]))
source(str_c(scriptPath, "/base.R"))

diffData <- read_tsv(opt$i)

diffData

if (nrow(diffData) == 0) {
  quit(status = 0)
}

diffNames <- diffData %>%
  .$Metabolite

selfCorTest = function(da1, method = "spearman") {
  name1 <- colnames(da1)
  tr_da1 <- as.matrix(da1)
  num1 <- ncol(da1)
  pvalue <- vector()
  value <- vector()
  id1 <- vector()
  id2 <- vector()
  rec <- 1
  for (i in 1:num1) {
    for (j in 1:num1) {
      a1 <- tr_da1[, i]
      a2 <- tr_da1[, j]
      id1[rec] <- name1[i]
      id2[rec] <- name1[j]
      a1 <- as.numeric(a1)
      a2 <- as.numeric(a2)
      corr <- cor.test(a1, a2, method = method)
      esti <- as.matrix(corr$estimate)[1]
      value[rec] <- esti
      pvalue[rec] <- corr$p.value
      rec <- rec + 1
    }
  }
  list(node1 = id1, node2 = id2, cor = value, p = pvalue)
}

orignalData <- diffData %>%
  as.data.frame()

configData <- read_tsv(opt$config, col_names = F) %>%
  set_colnames(c("arg", "value"))

corP <- configGet(configData, "p") %>%
  as.numeric()
corFdr <- configGet(configData, "fdr") %>%
  as.numeric()
cor <- configGet(configData, "coe") %>%
  as.numeric()
fdrMethod <- configGet(configData, "fdrMethod")
corMethod <- configGet(configData, "corMethod")

data <- orignalData %>%
  column_to_rownames("Metabolite") %>%
  as.data.frame()

data <- t(data)

parent <- "./"
createWhenNoExist(parent)
inData <- data %>%
  as.matrix()

listRs <- selfCorTest(inData, method = corMethod)

allData <- data.frame(Node1 = listRs$node1, Node2 = listRs$node2, r = listRs$cor, P = listRs$p,
                      stringsAsFactors = F) %>%
  mutate_at(vars(c("r")), function(x) {
    ifelse(is.na(x), 0, x)
  }) %>%
  mutate_at(vars(c("P")), function(x) {
    ifelse(is.na(x), 1, x)
  }) %>%
  mutate(FDR = p.adjust(P, method = fdrMethod))

corData <- allData %>%
  select(c("Node1", "Node2", "r")) %>%
  spread(Node1, "r") %>%
  rename(` ` = Node2)

write_csv(corData, paste0(parent, "/r_Matrix.csv"))

pData <- allData %>%
  select(c("Node1", "Node2", "P")) %>%
  spread(Node1, "P") %>%
  rename(` ` = Node2)

write_csv(pData, paste0(parent, "/P_Matrix.csv"))

fdrData <- allData %>%
  select(c("Node1", "Node2", "FDR")) %>%
  spread(Node1, "FDR") %>%
  rename(` ` = Node2)

write_csv(fdrData, paste0(parent, "/Corrected_P_Matrix.csv"))

edgeData <- allData %>%
  filter(P < corP & FDR < corFdr & abs(r) > cor) %>%
  filter(Node1 != Node2) %>%
  mutate(distName = {
    Node1 %>%
      map2_chr(Node2, function(x, y) {
        vec <- c(x, y) %>%
          sort()
        str_c(vec, collapse = ";")
      })
  }) %>%
  distinct(distName, .keep_all = T) %>%
  select(-c("distName")) %>%
  arrange(desc(abs(r)))

write_csv(edgeData, paste0(parent, "/Network_Edges_for_Cytoscape.csv"))

nodes <- unique(c(edgeData$Node1, edgeData$Node2))
infoData <- tibble(Node = nodes) %>%
  mutate(Size = {
    Node %>%
      map_int(function(x) {
        edgeData %>%
          filter(Node1 == x | Node2 == x) %>%
          nrow()
      })
  })

write_csv(infoData, paste0(parent, "/Network_Nodes_for_Cytoscape.csv"))



